package tabdulin.sms.contacts;

import java.io.FileWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import tabdulin.util.FileUtil;

/**
 * @author Talgat Abdulin
 *
 */
public class ContactList {
    private final static Logger logger = Logger.getLogger(ContactList.class);
    private final static String FILE_NAME = "contacts.xml";
    
    private List<Contact> contents = new LinkedList<Contact>();
    private List<ContactListListener> listeners = new LinkedList<ContactListListener>();
    
    public void load() {
        try {
            logger.info("Loading contacts from file \"" + FILE_NAME + "\" ...");
            if (!FileUtil.exists(FILE_NAME)) {
                logger.info("No such file was found, new contacts file will be generated.");
                return;
            }
            SAXReader saxReader = new SAXReader();
            Document contactsDocument = saxReader.read(FILE_NAME);
            Element contactsElement = contactsDocument.getRootElement();
            logger.debug("Number of contacts to load : " + contactsElement.elements().size());
            for (Iterator<?> i = contactsElement.elementIterator(); i.hasNext();) {
                Element contactElement = (Element) i.next();
                Contact contact = new Contact();
                contact.setOperator(contactElement.element("operator").getTextTrim());
                contact.setPrefix(contactElement.element("prefix").getTextTrim());
                contact.setNumber(contactElement.element("number").getTextTrim());
                contact.setName(contactElement.element("name").getTextTrim());
                add(contact);
            }
            logger.info("Contacts were loaded.");
        } catch (DocumentException e) {
            logger.error("No contacts were loaded.", e);
        }
    }
    
    public void save() {
        try {
            logger.info("Saving contacts...");
            XMLWriter xmlWriter = new XMLWriter(new FileWriter(FILE_NAME));
            Document contactsDocument = DocumentHelper.createDocument();
            Element contactsElement = contactsDocument.addElement("contacts");
            logger.debug("Number of contacts to save : " + contents.size());
            for (Contact contact : contents) {
                Element contactElement = contactsElement.addElement("contact");
                contactElement.addElement("operator").setText(contact.getOperator());
                contactElement.addElement("prefix").setText(contact.getPrefix());
                contactElement.addElement("number").setText(contact.getNumber());
                contactElement.addElement("name").setText(contact.getName());
            }
            xmlWriter.write(contactsDocument);
            xmlWriter.close();
            logger.info("Contacts were saved.");
        } catch (Exception e) {
            logger.error("Contacts were not saved.", e);
        }
    }

    public void add(Contact newContact) {
        contents.add(newContact);
        fireUpdate();
    }
    
    public void remove(int index) {
        contents.remove(index);
        fireUpdate();
    }
    
    public void addListener(ContactListListener newListener) {
        listeners.add(newListener);
    }
    
    public void removeListener(int index) {
        listeners.remove(index);
    }
    
    private void fireUpdate() {
        for (ContactListListener listener : listeners) {
            listener.update();
        }
    }

    public Contact get(int index) {
        return contents.get(index);
    }

    public int size() {
        return contents.size();
    }
}
